package com.bestv.search.common.service.impl;

import com.bestv.search.common.dao.SearchKeywordHistoryDao;
import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.SearchKeywordHistory;
import com.bestv.search.common.model.TopNCache;
import com.bestv.search.common.service.SearchKeywordHistoryManager;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class SearchKeywordHistoryManagerImpl implements SearchKeywordHistoryManager {

    private SearchKeywordHistoryDao searchKeywordHistoryDao;

    public SearchKeywordHistoryDao getSearchKeywordHistoryDao() {
        return searchKeywordHistoryDao;
    }

    public void setSearchKeywordHistoryDao(SearchKeywordHistoryDao searchKeywordHistoryDao) {
        this.searchKeywordHistoryDao = searchKeywordHistoryDao;
    }

    public void saveOrUpdateSearchKeywordHistory(DataSourceKey key, SearchKeywordHistory[] historyArray) {

        if (historyArray.length > 0) {
            // removes records first by date.
            searchKeywordHistoryDao.removeByDate(historyArray[0].getDate());

            // save all records to DB
            List<SearchKeywordHistory> list = Arrays.asList(historyArray);
            searchKeywordHistoryDao.saveObjectList(list);
        }
    }

    public List<String[]> getSearchKeywordHistoryByKeyword(DataSourceKey key, String keyword, Date startDate,
                                                           Date endDate, String type) {
        return searchKeywordHistoryDao.getSearchKeywordHistoryByKeyword(keyword, startDate, endDate, type);
    }

    public List<TopNCache> getKeywordTopNCache(DataSourceKey key, String type) {
        return searchKeywordHistoryDao.getKeywordTopNCache(type);
    }

    public Date getMaxDate(DataSourceKey key) {
        return searchKeywordHistoryDao.getMaxDate();
    }

    public void deleteHistroyByKeyword(DataSourceKey key, String keyword) {
        searchKeywordHistoryDao.deleteHistroyByKeyword(keyword);
    }
}